package com.dgshanger.sanhxiaofeisc.ui.nearby

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.dgshanger.sanhxiaofeisc.MainActivity
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.adapter.SearchAdapter
import com.dgshanger.sanhxiaofeisc.adapter.SearchHotAdapter
import com.dgshanger.sanhxiaofeisc.adapter.SearchResultAdapter
import com.dgshanger.sanhxiaofeisc.common.Constants
import com.dgshanger.sanhxiaofeisc.entity.NearbyItemEntity
import com.dgshanger.sanhxiaofeisc.entity.SearchHotEntity
import com.dgshanger.sanhxiaofeisc.mvp.contract.SearchContract
import com.dgshanger.sanhxiaofeisc.mvp.presenter.SearchPresenter
import com.dgshanger.sanhxiaofeisc.ui.home.activity.ShopDetailsActivity
import com.dgshanger.sanhxiaofeisc.ui.home.utils.ImageLoader
import com.xx.baseuilibrary.mvp.BaseMvpActivity
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.view_search_head.*
import kotlinx.android.synthetic.main.view_search_head.view.*


/**
 * SearchActivity
 * 沉迷学习不能自拔
 * Describe：
 * Created by 雷小星🍀 on 2018/4/19 13:36.
 */
class SearchActivity : BaseMvpActivity<SearchContract.Model,SearchContract.View,SearchPresenter>(),SearchContract.View {

    override fun createPresenter(): SearchPresenter = SearchPresenter()
    override fun getActivityLayoutId(): Int = R.layout.activity_search
    private lateinit var mAdapter : SearchAdapter
    private lateinit var mHotAdapter : SearchHotAdapter
    private  var mHistoryList : ArrayList<String>? =null
    private lateinit var mResultAdapter : SearchResultAdapter
    private lateinit var mLocation : Array<String>

    override fun initData() {
        if (Constants.isLogin()) {
            ImageLoader.loadAvatar(mContext, iv_search_avatar, Constants.getUserEntity()?.avatar)
        } else {
            iv_search_avatar.setImageResource(R.color.colorDivler)
        }
        mHistoryList= Constants.getHistorySearch()
        mLocation=Constants.getLocation()
        initView()
        getPresenter().loadHotData()
    }

    private fun initView() {
        //历史搜索
        recyclerView.layoutManager=LinearLayoutManager(mContext)
        if (mHistoryList==null){
            mAdapter= SearchAdapter(R.layout.item_history_search,ArrayList())
        }else{
            mAdapter= SearchAdapter(R.layout.item_history_search, mHistoryList!!)
        }

        mAdapter.addHeaderView(getHeaderView())
        recyclerView.adapter=mAdapter
    }

    private lateinit var mHeaderView : View

    private fun getHeaderView(): View? {
        mHeaderView = View.inflate(mContext, R.layout.view_search_head, null)
        //搜索结果
        mHeaderView.rec_result.layoutManager=LinearLayoutManager(mContext)
        mResultAdapter=SearchResultAdapter(R.layout.item_nearby_list,ArrayList())
        mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN)
        mHeaderView.rec_result.adapter=mResultAdapter
        //热门搜索
        mHeaderView.rec_hot.layoutManager=LinearLayoutManager(mContext)
        mHotAdapter=SearchHotAdapter(R.layout.item_hot_search,ArrayList())
        mHeaderView.rec_hot.adapter=mHotAdapter
        return mHeaderView
    }

    override fun initEvent() {
        //头像
        iv_search_avatar.setOnClickListener{
            val intent = Intent(mContext, MainActivity::class.java)
            intent.putExtra(Constants.KEY_INTENT_MAIN, MainActivity.INDEX_PERSON)
            startActivity(intent)
        }

        //热门搜索
        mHeaderView.rec_hot.addOnItemTouchListener(object : OnItemClickListener(){

            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val searchHotContent = mHotAdapter.data[position].hot_word
                et_search.setText(searchHotContent)
                searchData(searchHotContent)
                mHistoryList=moveItem(searchHotContent)//如果集合有相同元素则移动到第一位
                mAdapter.setNewData(mHistoryList)
                Constants.putHistorySearch(mHistoryList)
            }
        })

        //历史搜索
        recyclerView.addOnItemTouchListener(object : OnItemClickListener(){

            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val searchHistoryContent = mAdapter.data[position]
                et_search.setText(searchHistoryContent)
                searchData(searchHistoryContent)
                mHistoryList=moveItem(searchHistoryContent)//如果集合有相同元素则移动到第一位
                mAdapter.setNewData(mHistoryList)
                Constants.putHistorySearch(mHistoryList)
            }
        })

        //键盘确认键的监听
        et_search.setOnEditorActionListener(object : TextView.OnEditorActionListener{
            override fun onEditorAction(v: TextView?, actionId: Int, event : KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    val searchContent = et_search.text.toString().trim()
                    if (!TextUtils.isEmpty(searchContent)){
                        searchData(searchContent)
                        mHistoryList=moveItem(searchContent)//如果集合有相同元素则移动到第一位
                        mAdapter.setNewData(mHistoryList)
                        Constants.putHistorySearch(mHistoryList)
                    }
                }
                return false
            }
        })

        mHeaderView.rec_result.addOnItemTouchListener(object :OnItemClickListener(){
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val intent = Intent(mContext, ShopDetailsActivity::class.java)
                intent.putExtra("shop_id", mResultAdapter!!.data[position].shop_id)
                intent.putExtra("comment_score",mResultAdapter.data[position].comment_score)
                startActivity(intent)
            }
        })


    }

    /**
     * 元素移位
     */
    private fun moveItem(content : String ) : ArrayList<String>{
        if (mHistoryList==null){
            mHistoryList=ArrayList()
            mHistoryList!!.add(0,content)
        }else{
            val indexOf = mHistoryList!!.indexOf(content)
            if (indexOf!=-1){
                //如果集合有相同元素则移动到第一位
                mHistoryList!!.removeAt(indexOf)
                mHistoryList!!.add(0,content)
            }else{
                mHistoryList!!.add(0,content)
            }
        }
        if (mHistoryList!!.size>5){//只保留5个
            mHistoryList!!.removeAt(5)
        }
        return mHistoryList!!
    }

    /**
     * 搜索商品
     */
    private fun searchData(serachContent : String ?){
        getPresenter().search(mLocation[2],mLocation[1],mLocation[0],serachContent)
    }

    override fun setHotData(data: MutableList<SearchHotEntity>?) {
        mHotAdapter.setNewData(data)
    }

    override fun setSearchResult(data: MutableList<NearbyItemEntity>?) {
        ll_result.visibility=View.VISIBLE
        if (!data!!.isEmpty()){
            mResultAdapter.setNewData(data)
        }else{
            mResultAdapter.setNewData(data)
            mResultAdapter.emptyView = getEmptyView()
        }
    }

    private fun getEmptyView(): View? {
       return View.inflate(mContext,R.layout.view_search_empty,null)
    }

}